/**
 * useRef
 */
export default () => {
  let timer = useRef(null);
  const [currTime, setCurrTime] = useState(new Date().toLocaleTimeString());
  const clearTimer = () => {
    timer && clearInterval(timer.current);
  };
  useEffect(() => {
    timer.current = setInterval(() => {
      setCurrTime(new Date().toLocaleTimeString());
    }, 1000);
    return () => {
      clearTimer();
    };
  }, []);
  return (
    <>
      <p>当前时间：{currTime}</p>
      <button onClick={clearTimer}>停止更新时间</button>
    </>
  );
};

/**
 * useImperativeHandle
 */
function App() {
  const comRef = useRef(null);
  function handleClick() {
    comRef.current.handleClick();
  }
  return (
    <div>
      <ChildCom1 ref={comRef} />
      <button onClick={handleClick}>调用子组件方法</button>
    </div>
  );
}
function ChildCom1(props, ref) {
  const childRef = useRef(null);

  useImperativeHandle(ref, () => ({
    click: () => {
      console.log(childRef.current);
    },
  }));

  // 定义一个名为clickHandle的函数
  function clickHandle() {
    // 在控制台输出"子组件方法被调用"
    console.log("子组件方法被调用");
  }
  return (
    <div onClick={clickHandle} ref={childRef}>
      子组件
    </div>
  );
}
React.forwardRef(ChildCom1);
